package com.hll.spring_book.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hll.spring_book.annotion.logAnno;
import com.hll.spring_book.pojo.Category;
import com.hll.spring_book.service.category.CategoryService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author: Mr.Hu
 * @create: 2021-03-29 12:32
 */
@RequestMapping("/category")
@RestController
public class CategoryController {
  @Resource private CategoryService categoryService;

  @PostMapping("queryCategoriesByLimit")
  public PageInfo<Category> queryCategoriesByLimit(
      @RequestParam(defaultValue = "1", value = "pageNo") Integer pageNo,
      @RequestParam(defaultValue = "5", value = "pageSize") Integer pageSize) {
    PageHelper.startPage(pageNo, pageSize); /*分页插件，mapper看起来是查找全部，但被干预了*/
    return new PageInfo<>(categoryService.queryAll(new Category()));
  }

  @PostMapping("queryCategoriesAll")
  public List<Category> queryCategoriesAll() {
    return categoryService.queryAll(new Category());
  }

  @PostMapping("queryCategoryById")
  public Category queryCategoriesByLimit(@RequestParam("id") Integer id) {
    return categoryService.queryById(id);
  }

  @logAnno(description = "增加分类")
  @PostMapping("addCategory")
  public boolean addCategory(@RequestBody Category category) {
    if (!checkCategoryExist(category.getName())) return categoryService.insert(category) != null;
    return false;
  }

  @logAnno(description = "修改分类")
  @PostMapping("updateCategory")
  public boolean updateCategory(@RequestBody Category category) {
    return categoryService.update(category) != null;
  }

  @logAnno(description = "删除分类")
  @PostMapping("deleteCategory")
  public boolean deleteCategory(@RequestParam("id") Integer id) {
    return categoryService.deleteById(id);
  }

  // 是否存在分类
  @PostMapping("/checkExist")
  public boolean checkCategoryExist(@RequestParam("name") String name) {
    return categoryService.isCategoryExist(name);
  }
}
